import {
  Component, OnInit, ViewEncapsulation, ChangeDetectionStrategy, ViewChild, Renderer2,
  OnDestroy
} from '@angular/core';
import {ToolsService} from "@shared/service/tools/tools.service";
import {ActivatedRoute, Router} from "@angular/router";

import {SignUpService} from "@sign-up/sign-up.service";
import {ModalComponent} from "@shared/components/modal/modal.component";

import {Subject} from "rxjs/Subject";
import {DynamicFormDefault, MatchSignUpData, MatchSignupFieldsResp} from "@interface/index";


@Component({
  selector: 'sign-up-double-match',
  templateUrl: './sign-up-double-match.component.html',
  styleUrls: ['./sign-up-double-match.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class SignUpDoubleMatchComponent implements OnInit, OnDestroy {
  // 单双打字段： 男子单打:1, 女子单打：2, 男子双打：11, 女子双打：22 ,混双：12
  public params = new MatchSignUpData();
  public addition: MatchSignupFieldsResp[];
  public contactDefault: DynamicFormDefault;
  public showModal: boolean;
  public signing = false;
  public contactArr: Array<DynamicFormDefault> = [];
  private chooseIndex = -1;
  @ViewChild(ModalComponent) modal;
  private ngUnSubscribe: Subject<any> = new Subject<any>();
  private matchOrder: string;

  constructor(private toolsService: ToolsService,
              private route: ActivatedRoute,
              private router: Router,
              private signUpService: SignUpService,
              private renderer: Renderer2) {

    this.route.queryParams.subscribe(param => {
      // this.params = {
      //   matchId: param['matchId'],
      //   orderNumber: param['orderNumber'],
      //   channelsId: param['channelsId'],
      //   groupType: param['goodsType'],
      //   matchOrder: param['matchOrder']
      // };
      this.params.matchId = param['matchId'];
      this.params.orderNumber = param['orderNumber'];
      this.params.channelsId = param['channelsId'];
      this.params.groupType = param['groupType'];
      this.matchOrder = param['matchOrder'];
    });
  }

  ngOnInit() {
    this.getData();
    this.renderer.listen('window', 'popstate', this.popstateHandler.bind(this));
  }

  /**
   * 根据type 参数来获取 参赛类型
   * @returns {string}
   */
  getSignType() {
    return this.signUpService.getDoubleMatchSignType(this.matchOrder);
  }

  getData() {
    this.signUpService.getDynamicMatchInfo(this.params.matchId, this.params.orderNumber)
      .subscribe(res => {
        if (res.result === '0') {
          if (res.data.matchSignupFields.length > 0) {
            this.addition = res.data.matchSignupFields;
          }
        }
      });
  }

  edit(i: number) {
    this.chooseIndex = i;
    this.contactDefault = this.contactArr[i];
    this.modal.show();
    this.showModal = true;
  }

  add() {
    this.modal.show();
    this.showModal = true;
  }

  saveForm(item) {
    if (this.chooseIndex >= 0) {
      this.contactArr.splice(this.chooseIndex, 1, item);
    } else {
      this.contactArr.unshift(item);
    }
    this.reset();
  }

  reset() {
    this.chooseIndex = -1;
    this.contactDefault = null;
    this.modal.hide();
    this.modal.goBack();
    this.showModal = false;
  }

  delCustomer() {
    this.contactArr.splice(this.chooseIndex, 1);
    this.reset();
  }

  sign() {
    if (this.signing) {
      return;
    }
    this.signing = true;
    const data = this.signUpService.getPerasonalSignData(this.params);

    data['matchSignDataReqList'] = this.contactArr;
    this.toolsService.showLoading();
    this.signUpService
      .toSign(data)
      .subscribe((res) => {
        this.signing = false;
        this.toolsService.hideLoading();
        if (res['result'] === '0') {
          // if (res.data.orderStatus === 2) {
          //   this.router.navigate(['/payment/result'], {queryParams: {mchOrderNumber: this.params.orderNumber}});
          // } else {
          //   this.router.navigate(['/payment'], {queryParams: {orderNumber: this.params.orderNumber}});
          // }
          this.signUpService.goToPayOrResult(res.data.orderStatus, this.params.orderNumber);
        } else if (res.result === '9012') {
          this.toolsService.showToast('该商品已下架');
        } else if (res.result === '13002') {
          this.toolsService.showToast('提交失败，请查看订单状态是否正常');
        } else if (res.result === '9092') {
          const msgData = this.signUpService.getAgeLimitMsg(res.data);
          const temp = {
            title: `参赛人年龄不符 ${msgData.minAge} ~ ${msgData.maxAge} 岁`,
            message: `报名人: ${msgData.memberStr}`
          };
          this.toolsService.present(temp);
        } else if (res.result === '9067') {  // 用户已报名了;
          const str = this.signUpService.getHasSignMemberStr(res.data);
          const temp = {
            title: '用户已报名',
            message: str
          };
          this.toolsService.present(temp);
        } else if (res.result === '9102') {  // 性别不符
          const temp = {
            title: '参赛人员性别不符',
            message: res.msg
          };
          this.toolsService.present(temp);
        } else {
          this.toolsService.showToast(res.msg);
        }
      });
  }

  // 返回时重置一次所有参数
  popstateHandler() {
    this.chooseIndex = -1;
    this.contactDefault = null;
    this.showModal = false;
  }

  ngOnDestroy() {
    this.ngUnSubscribe.next();
    this.ngUnSubscribe.complete();
  }
}
